//
//  CSHTTPProgressValueWork.m
//  花式下载文件
//
//  Created by 姚彦兆 on 15/10/21.
//  Copyright © 2015年 姚彦兆. All rights reserved.
//

#import "CSHTTPProgressValueWork.h"

#import <UIKit/UIKit.h>



@interface CSHTTPProgressValueWork ()<NSURLSessionDownloadDelegate>

@property (nonatomic, strong) NSURLSession * mySession ;

@property (nonatomic, strong) NSURLSessionDownloadTask * downloadTask ;

@property (nonatomic, strong) NSData * resumeData ;

@property (nonatomic, copy) NSString * savePath ;

//定义一个全局的Block(获得声明过的Block)
@property (nonatomic, copy) progressValueBlock progressBlock ;

@end

@implementation CSHTTPProgressValueWork


-(void)getCSProgressViewWithDownloadURLString:(NSString *)urlSTR
                                  andSavePath:(NSString *)savePath
                         andProgressViewValue:(progressValueBlock)progressBlock{
    
    self.progressBlock = progressBlock ;
    
    //创建下载链接URLNSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://dldir1.qq.com/qqfile/QQforMac/QQ_V4.0.4.dmg"]];
    
    self.savePath = [NSString stringWithString:savePath];
    
    NSURL * url = [NSURL URLWithString:urlSTR];
    
    //创建下载链接的网络请求
    NSURLRequest * request = [NSURLRequest requestWithURL:url];
    
    //根据URLSession实例化task对象
    NSURLSessionDownloadTask * task = [self.mySession downloadTaskWithRequest:request];
    
    self.downloadTask = task ;
    //开始下载任务
    
    [task resume];
    
    
}

/**
 *  下载的时候会调用该方法(不断写入数据不断调用)
 *
 *  @param session                   当前的Session
 *  @param downloadTask              当前的downloadTask
 *  @param bytesWritten              本次写入的数据量
 *  @param totalBytesWritten         已经下载的数据量
 *  @param totalBytesExpectedToWrite 总的数据量
 */
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
    
    NSLog(@"--------------------%lld" , bytesWritten);
    
    float progressValue = (float)totalBytesWritten / totalBytesExpectedToWrite ;
    
    float percentValue = progressValue * 100 ;
    
    if (self.progressBlock) {
        
        self.progressBlock(percentValue);
        
//        self.progressValueBlock = nil ;
        
    }

}

//下载完毕后会执行这个方法,这个方法执行之后就会自动删除在location中保存的文件
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{
    
    NSLog(@"下载完成---%@" , location);
    
    [[NSFileManager defaultManager] copyItemAtPath:location.path toPath:[NSString stringWithString:self.savePath] error:NULL];
    
}

- (NSURLSession *)mySession
{
    if (!_mySession) {
        _mySession = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    }
    return _mySession;
}

@end
